#include "abstract-database-client.h"
#include "contractor-section-model.h"
#include "contractor-section-queries.h"
#include "line-edit-delegate.h"
#include "value-result.h"

ContractorSectionModel::ContractorSectionModel(QObject *parent) :
    StandardDatabaseModel(parent)
{
}

void ContractorSectionModel::initialize()
{
    m_queries = new ContractorSectionQueries(this);
    LineEditDelegate* nameDelegate = new LineEditDelegate(this);
    LineEditDelegate* nipDelegate = new LineEditDelegate(this);
    LineEditDelegate* regonDelegate = new LineEditDelegate(this);
    LineEditDelegate* streetDelegate = new LineEditDelegate(this);
    LineEditDelegate* postalCodeDelegate = new LineEditDelegate(this);
    LineEditDelegate* cityDelegate = new LineEditDelegate(this);
    LineEditDelegate* telephoneDelegate = new LineEditDelegate(this);
    m_delegates.insert(NameColumn, nameDelegate);
    m_delegates.insert(NipColumn, nipDelegate);
    m_delegates.insert(RegonColumn, regonDelegate);
    m_delegates.insert(StreetColumn, streetDelegate);
    m_delegates.insert(PostalCodeColumn, postalCodeDelegate);
    m_delegates.insert(CityColumn, cityDelegate);
    m_delegates.insert(TelephoneColumn, telephoneDelegate);
    m_headerSections << "Nazwa" << "NIP" << "REGON" << "Ulica" << "Kod pocztowy" << "Miasto" << "Telefon";
    m_dataAlreadyExistText = "Kontrahent o takich danych już istnieje.";
    StandardDatabaseModel::initialize();
}

ValueResult* ContractorSectionModel::canSetField (QVariant value, int column, int row)
{
    Q_UNUSED(row);
    ValueResult* result = new ValueResult(this);
    if (column == NameColumn)
    {
        QString name(value.toString());
        if (name.isEmpty())
            result->setError("Nazwa kontrahenta jest pusta.", SmGlobal::DataInvalidError);
        else
            result->setValue(true);
    }
    else
    {
        result->setValue(true);
    }
    return result;
}

ValueResult* ContractorSectionModel::canSetRow (QVariantList dataList, int row)
{
    Q_UNUSED(row);
    ValueResult* result = m_databaseClient->selectExists(m_queries->existsQuery(), QVariantList() << id(row) << dataList.at(NameColumn));
    connect (result, &ValueResult::resultReady, this, &ContractorSectionModel::finishCanSetRow);
    ValueResult* outerResult = new ValueResult(this);
    result->setRequestData(QVariant::fromValue(outerResult));
    return outerResult;
}
